//
//  MessageBoardViewController.m
//  YinHang
//
//  Created by idea on 14-9-17.
//  Copyright (c) 2014年 孙彦鹏. All rights reserved.
//

#import "MessageBoardViewController.h"
#import "AddMessageViewController.h"

#import "Message.h"
#import "GetMessage.h"

#import "MessageCell.h"

@interface MessageBoardViewController ()<UITableViewDelegate,UITableViewDataSource,UIAlertViewDelegate,addOrAlterMessageDelegate,messageServiceDelegate>{
    
    NSMutableArray *messageArr;
    Message *message;
    NSUInteger btnTag;
    
    GetMessage *messageService;//获取数据
    
    ASIFormDataRequest *delRequest_;//删除请求
    ASIFormDataRequest *updateState_;//修改状态
    
}

@end

@implementation MessageBoardViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    //self.navigationController.navigationBarHidden = NO;
    self.navigationItem.title = @"留言板";
    
    UIButton *leftBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 20, 30)];
    [leftBtn setBackgroundImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:leftBtn];
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    negativeSpacer.width = - 10;
    if (ios7) {
        self.navigationItem.leftBarButtonItems = @[negativeSpacer,leftBarButtonItem];
    }else{
        self.navigationItem.leftBarButtonItems = @[leftBarButtonItem];
    }
    
    /*//功能修改
    //添加
    UIButton *addBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    addBtn.frame = CGRectMake(0, 0, 30, 30);
    [addBtn setTitle:@"添加" forState:UIControlStateNormal];
    addBtn.titleLabel.textColor = [UIColor whiteColor];
    [addBtn addTarget:self action:@selector(add) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *addBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:addBtn];
    self.navigationItem.rightBarButtonItem = addBarButtonItem;
    */
    // 屏幕适配
    _messageBoardTableView.frame = CGRectMake(_messageBoardTableView.frame.origin.x, _messageBoardTableView.frame.origin.y, _messageBoardTableView.bounds.size.width, self.view.bounds.size.height - _messageBoardTableView.frame.origin.y );
    _messageBoardTableView.rowHeight = 84;
    [self setUI];
    [self getdate];
    [self setupRefresh];
    [_messageBoardTableView headerBeginRefreshing];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    
    
    
}

#pragma mark - Custom Method

-(void)setUI{
    _messageBoardTableView.dataSource = self;
    _messageBoardTableView.delegate = self;
//    _messageBoardTableView.rowHeight = 88;
}
//获取message
-(void)getdate{
    messageService = [[GetMessage alloc]init];
    messageArr = messageService.pageInfo.dataArr;
    messageService.delegate = self;
}
//返回
-(void)back{
    //self.navigationController.navigationBarHidden = YES;
    [self.navigationController popViewControllerAnimated:YES];
}
/*
//添加
-(void)add{
    AddMessageViewController *amvc = [[AddMessageViewController alloc]initWithNibName:@"AddMessageViewController" bundle:nil];
    amvc.delegate = self;
    amvc.navTitle = @"添加链接";
    [self.navigationController pushViewController:amvc animated:YES];
}
*/

//修改留言
/*
-(void)alterCell:(id)sender{
    
    UIButton *btn = sender;
    NSLog(@"%i",btn.tag);
    NSInteger row = btn.tag - 10;
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:messageArr.count inSection:1];
    
    AddMessageViewController *amvc = [[AddMessageViewController alloc]initWithNibName:@"AddMessageViewController" bundle:nil];
    amvc.delegate = self;
    amvc.selectRow = row;
    amvc.navTitle = @"修改链接";
    [self.navigationController pushViewController:amvc animated:YES];
    
    [_messageBoardTableView deselectRowAtIndexPath:indexPath animated:YES];
}*/
//删除留言
-(void)deleteCell:(id)sender{
    UIButton *btn = sender;
    NSLog(@"%i",btn.tag);
    btnTag = btn.tag - 10;
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"是否删除此条信息？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alert show];
}
#pragma mark - UIAlertViewDelegate
//删除处理
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
        // 检查网络
        if (![Constants isExistenceNetwork]) {
            
        } else {
            delRequest_ = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:API_STR]];
            delRequest_.requestMethod = @"POST";
            // 设置超时时间
            delRequest_.timeOutSeconds = 30;
            delRequest_.delegate = self;
            // 设置参数
            NSString *action = @"liuyandel";
            NSDictionary *paramsDict =  @{@"lid":messageService.pageInfo.dataArr[btnTag][@"lid"], @"uid": UNAME};
            NSString *paramsStr = [NSString JSONString:paramsDict];
            NSString *result = [NSString stringWithFormat:TEMPLATE_PARAMSTR, action,paramsStr];
            
            NSData *paramsData = [result toGBKEncodingData];
            delRequest_.postBody = [paramsData mutableCopy];
            
            [delRequest_ startAsynchronous];
        }

        //[messageArr removeObjectAtIndex:btnTag];
        //[_messageBoardTableView reloadData];
        
        
    }
}

#pragma mark - ASIHTTPRequestDelegate Method

- (void)requestFinished:(ASIHTTPRequest *)request {
    //NSLog(@"%@",request.responseString);
    NSError *err;
    NSDictionary *result = [NSJSONSerialization JSONObjectWithData:[request.responseString dataForUTF8] options:NSJSONReadingAllowFragments error:&err];
    
    // 1. 是否解析有错误
    if (!err) {
        
        // 2. 判断错误码
        NSInteger errorCode = [result[@"errorCode"]integerValue];
        if (errorCode == 0) {
            //获取选中删除行索引值并通过获取的索引值删除数组中的值
            [messageService.pageInfo.dataArr removeObjectAtIndex:btnTag];
            //删除单元格的某一行时，在用动画效果实现删除过程
            [_messageBoardTableView deleteRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:btnTag inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
            [_messageBoardTableView reloadData];
            
            [SVProgressHUD showSuccessWithStatus:@"删除成功"];
            
        } else {
            [SVProgressHUD showErrorWithStatus:result[@"errorMsg"]];
        }
    } else {
        [SVProgressHUD showErrorWithStatus:@"数据解析出错！"];
    }
}

- (void)requestFailed:(ASIHTTPRequest *)request {
    [SVProgressHUD showErrorWithStatus:@"服务器无法访问，请稍后再试!"];
}



#pragma mark - UITableViewDelegate Method

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (messageService.pageInfo.dataArr.count != 0) {
        return messageService.pageInfo.dataArr.count;
    }else{
        return 0;
    }
    
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellId = @"MessageCell";
    
    MessageCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (!cell) {
        cell = [[NSBundle mainBundle]loadNibNamed:@"messageCell" owner:nil options:nil][0];
        //添加图片
        UIImageView *img_view = (UIImageView *)[cell.contentView viewWithTag:1];
        img_view.image = [UIImage imageNamed:@"item_64"];
    }
    NSUInteger row = [indexPath row];
    //message = messageArr[row];
    
    
    [cell.deleteCell addTarget:self action:@selector(deleteCell:) forControlEvents:UIControlEventTouchUpInside];//删除留言
    cell.deleteCell.tag = row + 10;

    
    UILabel *lblName = (UILabel *) [cell.contentView viewWithTag:2];
    UILabel *lblState = (UILabel *) [cell.contentView viewWithTag:3];
    UILabel *lblTime = (UILabel *) [cell.contentView viewWithTag:4];
    if (messageService.pageInfo.dataArr.count != 0 ) {
        lblName.text = messageService.pageInfo.dataArr[row][@"ltitle"];
        lblTime.text = messageService.pageInfo.dataArr[row][@"ltime"];
        if ((int)(messageService.pageInfo.dataArr[row][@"lstate"]) == 1) {
            lblState.text = @"已阅读";
        }else{
            lblState.text = @"未阅读";
        }
        

    }  
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    AddMessageViewController *amvc = [[AddMessageViewController alloc]initWithNibName:@"AddMessageViewController" bundle:nil];
    //amvc.delegate = self;
    NSInteger row = indexPath.row;
    amvc.selectRow = indexPath.row;
    amvc.navTitle = @"留言详情";
    amvc.lid = messageService.pageInfo.dataArr[row][@"lid"];
    amvc.messageTitle_ = messageService.pageInfo.dataArr[row][@"ltitle"];
    amvc.messageContent_ = messageService.pageInfo.dataArr[row][@"lcontent"];
    amvc.messageAuthor_ = messageService.pageInfo.dataArr[row][@"lname"];
    amvc.laddr = messageService.pageInfo.dataArr[row][@"laddr"];
    amvc.ltel = messageService.pageInfo.dataArr[row][@"ltel"];
    amvc.lemail = messageService.pageInfo.dataArr[row][@"lemail"];
    [self.navigationController pushViewController:amvc animated:YES];
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

/**
 *  集成刷新控件
 */
- (void)setupRefresh
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [_messageBoardTableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    /* 自动刷新(一进入程序就下拉刷新) */
    //[_tableView headerBeginRefreshing];
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [_messageBoardTableView addFooterWithTarget:self action:@selector(footerRereshing)];
}

#pragma mark 开始进入刷新状态
- (void)headerRereshing
{
    // 刷新表格
    [_messageBoardTableView reloadData];
    
    // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
    [_messageBoardTableView headerEndRefreshing];
    // 检查网络
    if (messageService.isQuery || ![Constants isExistenceNetwork]) {
     
     // 刷新表格
     [_messageBoardTableView reloadData];
     
     // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
     [_messageBoardTableView headerEndRefreshing];
     
     return;
     }
     
     // 下拉刷新 （请求第一页数据）
     
     // 每次必须重置下 否则会数据混乱
     messageService.pageInfo.pageno = @"1";
     [messageService pageQuery];
}

- (void)footerRereshing
{
    // 检查网络
     if (![Constants isExistenceNetwork]) {
     
     // 刷新表格
     [_messageBoardTableView reloadData];
     
     // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
     [_messageBoardTableView footerEndRefreshing];
     
     return;
     }
     
     // 如果正在查询 或 没有更多数据了
     if (messageService.isQuery || !messageService.pageInfo.hasMoreData) {
     // 2. 1秒后刷新表格UI
     dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
     // 刷新表格
     [_messageBoardTableView reloadData];
     
     // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
     [_messageBoardTableView footerEndRefreshing];
     
     MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
     hud.labelText = @"没有更多数据了";
     [hud hide:YES afterDelay:1];
     });
     
     messageService.pageInfo.hasMoreData = YES;
     
     return;
     }
     
     // 如果还有更多数据 请求下一页
     [messageService.pageInfo nextPage];
     [messageService pageQuery];
    
    // 刷新表格
    [_messageBoardTableView reloadData];
    
    // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
    [_messageBoardTableView headerEndRefreshing];
}


/*
#pragma mark - AddOrAlterMessageDelegate Method
//添加message
-(void)addMessageWithName:(NSString *)messageTitle MessageContent:(NSString *)messageContent{
    Message *_message = [[Message alloc]initWithMessageTitle:messageTitle messageContent:messageContent];
    [messageArr addObject:_message];
    [_messageBoardTableView reloadData];
}
//修改message
-(void)alterMessageAtRow:(NSInteger)row withMessageTitle:(NSString *)messageTitle MessageContent:(NSString *)messageContent{
    Message *_message = [[Message alloc]initWithMessageTitle:messageTitle messageContent:messageContent];
    [messageArr setObject:_message atIndexedSubscript:row];
    [_messageBoardTableView reloadData];
}
*/

#pragma mark - QuestionService Delegate

- (void)didRecieveData{
    [_messageBoardTableView headerEndRefreshing];
    [_messageBoardTableView footerEndRefreshing];
    [_messageBoardTableView reloadData];
}
- (void)didRecieveMsg{
    [_messageBoardTableView headerEndRefreshing];
    [_messageBoardTableView footerEndRefreshing];
    [_messageBoardTableView reloadData];
}

-(void)dealloc{
    messageService = nil;
    [delRequest_ cancel];
    [updateState_ cancel];
}
@end
